<template>
	<view class="long-categories">
		<!-- 搜索栏 -->
		<view class="long-search">
			<view class="long-searchCent">
				<image src="/static/haoIndexListImg/search.png" class="long-searchImg"></image>
				<input type="text" v-model="inputKey" @input="searchInput" placeholder="搜索你想要的服务"
					class="long-searchInput" />
			</view>
		</view>

		<!-- 主内容区（左右布局） -->
		<view class="uni-flex">
			<!-- 左侧分类 -->
			<view class="left">
				<scroll-view scroll-y :scroll-with-animation="true" :style="{ height: `${scrollHeight}px` }">
					<view class="left-item" v-for="(item, index) in list" :key="index"
						:class="{ 'left-item-active': index == active }" @click="categoryClick(item, index)">
						{{ item.name }}
						<view v-show="isShowNum" class="num" v-if="Object.keys(item.selectedIds).length > 0">
							{{ Object.keys(item.selectedIds).length }}
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 右侧内容列表 -->
			<view class="right">
				<scroll-view scroll-y scroll-with-animation :scroll-into-view="cIndex" @scroll="scroll"
					@scrolltolower="scrollToBottom" :style="{ height: `${scrollHeight}px` }" :enhanced="true"
					:bounces="false">
					<view class="right-content">
						<view class="right-container" v-for="(item, index) in list" :key="index" :id="`cid${item.id}`">
							<!-- 二级类目 -->
							<view class="category-content" v-for="(level2, level2Index) in item.children"
								:key="level2Index">
								<view class="level2-name">{{ level2.name }}</view>

								<!-- 三级类目 -->
								<view class="level3-items">
									<view v-for="(level3, level3Index) in level2.children" :key="level3Index"
										class="right-item" :class="{ 
                      'right-item-active': level3.checked, 
                      'right-item-disable': level3.disabled 
                    }" @click="itemClick(item, level2, level3)">
										{{ level3.name }}
									</view>
								</view>
							</view>
						</view>

						<!-- 底部填充视图，确保能滚动到底部 -->
						<view class="bottom-placeholder" :style="{ height: `${safeAreaBottom + 100}px` }"></view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		name: "category",
		data() {
			return {
				inputKey: '',
				active: 0,
				cIndex: "",
				topList: [],
				flag: false,
				scrollHeight: 0, // 滚动区域高度
				safeAreaBottom: 0, // 底部安全区域高度
				statusBarHeight: 0, // 状态栏高度
				windowHeight: 0 // 窗口高度
			};
		},
		props: {
			list: {
				type: Array,
				default: () => []
			},
			maxSelected: {
				type: [String, Number],
				default: "-1"
			},
			isShowNum: {
				type: Boolean,
				default: false
			}
		},
		methods: {
			scroll(e) {
				if (this.flag) {
					this.flag = false;
					return;
				}
				const scrollTop = e.detail.scrollTop;
				for (let i = 0; i < this.topList.length; i++) {
					const h1 = this.topList[i];
					const h2 = this.topList[i + 1] || Infinity;
					if (scrollTop >= h1 && scrollTop < h2) {
						this.active = i;
						break;
					}
				}
			},
			categoryClick(category, index) {
				this.active = index;
				this.$nextTick(() => {
					this.cIndex = `cid${category.id}`;
					this.flag = true;
				});
			},
			itemClick(level1, level2, level3) {
				if (level3.disabled) return;
				const checked = !level3.checked;
				// if (checked && this.maxSelected !== "-1" && this.getValues().length >= Number(this.maxSelected)) {
				//   uni.showToast({ icon: "none", title: `最多可选${this.maxSelected}个` });
				//   return;
				// }
				level3.checked = checked;
				if (checked) {
					level1.selectedIds[level3.id] = level3;
				} else {
					delete level1.selectedIds[level3.id];
				}
				this.getSelectedCount();
			},
			getValues() {
				let ids = [];
				this.list.forEach(item => {
					ids = ids.concat(Object.values(item.selectedIds));
				});
				return ids;
			},
			getSelectedCount() {
				const ids = this.getValues();
				this.$emit("change", JSON.parse(JSON.stringify(ids)));
			},
			getNodesInfo() {
				const query = uni.createSelectorQuery().in(this);
				query.selectAll('.right-container').boundingClientRect(rects => {
					this.topList = rects.map(item => item.top);
				}).exec();
			},
			scrollToBottom() {
				this.active = this.list.length - 1;
			},
			reload() {
				this.getNodesInfo();
			},
			calculateHeight() {
				// 获取系统信息
				uni.getSystemInfo({
					success: (res) => {
						this.statusBarHeight = res.statusBarHeight || 0;
						this.windowHeight = res.windowHeight;

						// 计算搜索栏高度（rpx转px）
						const searchBarHeight = uni.upx2px(72 + 20 + 21);

						// 获取安全区域信息
						if (res.safeArea) {
							this.safeAreaBottom = res.windowHeight - res.safeArea.bottom;
						} else {
							this.safeAreaBottom = uni.upx2px(34); // 默认给底部留34px安全区域
						}

						// 计算滚动区域高度：窗口高度 - 搜索栏高度
						this.scrollHeight = res.windowHeight - searchBarHeight;

						// 确保scrollHeight至少为1px，避免渲染问题
						this.scrollHeight = Math.max(1, this.scrollHeight);
					}
				});
			}
		},
		mounted() {
			this.calculateHeight();
			this.getNodesInfo();
			setTimeout(() => {
				this.getSelectedCount();
			}, 500);
		},
		watch: {
			list: {
				deep: true,
				handler() {
					this.$nextTick(() => {
						this.getNodesInfo();
					});
				}
			}
		}
	};
</script>

<style lang="less" scoped>
	.long-categories {
		width: 100%;
		min-height: 100vh;
		background-color: #fff;
		display: flex;
		flex-direction: column;
	}

	/* 搜索栏样式 */
	.long-search {
		padding: 20rpx 24rpx 21rpx;
		background-color: #fff;
		flex-shrink: 0;

		.long-searchCent {
			height: 72rpx;
			background-color: #F1F1F1;
			border-radius: 36rpx;
			padding: 0 33rpx;
			display: flex;
			align-items: center;

			.long-searchImg {
				width: 32rpx;
				height: 32rpx;
				margin-right: 25rpx;
			}

			.long-searchInput {
				flex: 1;
				height: 100%;
				font-size: 28rpx;
				color: #999;
			}
		}
	}

	/* 左右布局容器 */
	.uni-flex {
		display: flex;
		flex: 1;
		overflow: hidden;
	}

	/* 左侧分类 */
	.left {
		width: 194rpx;
		background: #F1F1F1;
		height: 100%;
		overflow: hidden;

		scroll-view {
			height: 100%;
		}

		.left-item {
			height: 90rpx;
			display: flex;
			align-items: center;
			justify-content: space-evenly;
			padding: 0 10rpx;
			font-size: 30rpx;
			color: #333;
			position: relative;

			&.left-item-active {
				background: #fff;
				color: #2F80ED;
				font-weight: bold;
			}

			.num {
				width: 38rpx;
				height: 38rpx;
				line-height: 38rpx;
				background: #f67124;
				border-radius: 50%;
				color: #fff;
				font-size: 16rpx;
				text-align: center;
				position: absolute;
				right: 10rpx;
			}
		}
	}

	/* 右侧内容区 */
	.right {
		flex: 1;
		height: 100%;
		overflow: hidden;

		scroll-view {
			height: 100%;
			width: 100%;
		}

		.right-content {
			padding: 0 34rpx;
			box-sizing: border-box;

			.right-container {
				padding-bottom: 30rpx;

				.category-content {
					margin-bottom: 69rpx;

					.level2-name {
						font-weight: bold;
						font-size: 32rpx;
						color: #333;
						margin: 20rpx 0 10rpx;
					}

					.level3-items {
						display: flex;
						flex-wrap: wrap;

						.right-item {
							width: 45%;
							margin: 20rpx 20rpx 0 0;
							padding: 15rpx 0;
							text-align: center;
							background: #F1F1F1;
							border-radius: 6rpx;
							font-size: 28rpx;
							color: #333;
							box-sizing: border-box;

							&.right-item-active {
								background: #E5F0FF;
								color: #2F80ED;
							}

							&.right-item-disable {
								background: #efefef;
								color: #666;
							}
						}
					}
				}
			}

			.bottom-placeholder {
				width: 100%;
				background-color: transparent;
			}
		}
	}
</style>